package css.util;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileFilter;

import css.core.Record;

import java.io.*;
public class FileSaver{     

	 class filter extends FileFilter{
    	 private String extension;
    	 public filter(String extension){
    		 this.extension=extension;
    	 }
    	 public boolean accept(File file) {

    		   if (file.isDirectory())
    		   {
    		    return true;
    		   }

    		
    		   String fileName = file.getName();
    		   int index = fileName.lastIndexOf('.');

    		   if (index > 0 && index < fileName.length() - 1)
    		   {
    		    String fileext = fileName.substring(index + 1).toLowerCase();
    		    if (fileext.equals(extension))
    		     return true;
    		   }
    		   return false;
    	 }
    	 public String getDescription() {
               return "Record text file";
    	 }     
    	   
     }
	 
     public void save(Record record,JFrame pf){
    	 JFileChooser fc=new JFileChooser(".");
    	
    	 fc.setAcceptAllFileFilterUsed(false);
    	 

    	 
    	 fc.addChoosableFileFilter(new filter("txt"));
    	 int reval=fc.showSaveDialog(pf);
    	 if(reval==JFileChooser.APPROVE_OPTION){
    		 try{
    			 
    			 File file=fc.getSelectedFile();
    			 String path=file.getAbsolutePath();
    			 int index=path.lastIndexOf('.');
    			 if(index==-1){
    				 path=path.concat(".txt");
    			 }
    			 else if(index==path.length()-1){
    				 path=path.concat("txt");
    			 }
    			 else{
    				 String fileext=path.substring(index+1, path.length());
    				 if(!fileext.equals("txt")){
    					 path=path.concat(".txt");
    				 }
    			 }
    			 
    			 FileOutputStream fs=new FileOutputStream(new File(path));
    			 PrintWriter pw=new PrintWriter(fs);
    			 pw.write(record.toString());
    			 pw.close();
    		 }catch(IOException e){e.printStackTrace();}
    	 }
     }
}